package com.busi.utils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class DHCoderUtil {

	private static final Base64.Decoder decoder = Base64.getDecoder();
	private static final Base64.Encoder encoder = Base64.getEncoder();

	// 甲方公钥
	private static byte[] publicKey1;
	// 甲方私钥
	private static byte[] privateKey1;
	// 甲方本地密钥
	private static byte[] key1;
	// 乙方公钥
	private static byte[] publicKey2;
	// 乙方私钥
	private static byte[] privateKey2;
	// 乙方本地密钥
	private static byte[] key2;

	// 初始化密钥
	static {
		// 生成甲方密钥对
		Map<String, Object> keyMap1 = DHCoder.initKey();
		publicKey1 = DHCoder.getPublicKey(keyMap1);
		privateKey1 = DHCoder.getPrivateKey(keyMap1);
		// 由甲方公钥产生本地密钥对
		Map<String, Object> keyMap2 = DHCoder.initKey(publicKey1);
		publicKey2 = DHCoder.getPublicKey(keyMap2);
		privateKey2 = DHCoder.getPrivateKey(keyMap2);
		key1 = DHCoder.getSecretKey(publicKey2, privateKey1);
		key2 = DHCoder.getSecretKey(publicKey1, privateKey2);
	}

	// 使用甲方本地密钥对数据加密
	public static Map<String, Object> encrypt(File srcFileName, File destFileName) {
		// 使用甲方本地密钥对数据进行加密
		File code = DHCoder.encryptFile(srcFileName, destFileName, key1);
		Map<String, Object> map = new HashMap<String, Object>();
		System.out.println("加密文件路径：" + code.getPath());
		map.put("filePath", code.getPath());
		try {
			map.put("content", Files.readAllBytes(code.toPath()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		map.put("key1", encoder.encodeToString(key1));
		map.put("key2", encoder.encodeToString(key2));
		return map;
	}

	// 使用乙方本地密钥对数据解密
	public static File decrypt(File sourceFile, File decryptFile, String key) {
		byte[] key2 = decoder.decode(key);
		File decode = DHCoder.decryptFile(sourceFile, decryptFile, key2);
		return decode;
	}
}
